package org.papervision3d.materials
{
	import flash.display.Sprite;
	import flash.display.Bitmap;
	import flash.display.Shape;
	import flash.display.BlendMode;
	import flash.display.BitmapData;
	import flash.display.Graphics;
	import flash.geom.Matrix;
	import flash.geom.Rectangle;
	
	public class WallPaperMaterial extends MovieMaterial
	{
		
		public var rect : 			Rectangle;
		public var paperLayer : 	Sprite;
		
		public function WallPaperMaterial(baseMaterial : BitmapMaterial, transparent:Boolean=false, quality : Number = 1)
		{
			this.quality = quality;
			initMovie( baseMaterial, quality );
			super( wpmovie, transparent );
			fillColor = 0xffffff;
		}
		
		public function setMotif( bd : BitmapData, scale : Number = -1 ) : void {
			if( paperbd != null && paperbd != bd )paperbd.dispose();
			if( scale == -1 ) scale = _scale;
			else _scale = scale;
			paperbd = bd;
			var g : Graphics = paperLayer.graphics;
			g.clear();
			var m : Matrix = new Matrix();
			m.scale( scale, scale );
			g.beginBitmapFill( bd, m, true, true );
			if( rect ) g.drawRect( rect.x,rect.y,rect.width, rect.height );
			else g.drawRect( 0,0,wallLayer.width, wallLayer.height );
			g.endFill();
			
			updateBitmap();
		}
		
		public function setScale( scale : Number ) : void {
			trace(scale);
			_scale = scale * quality;
			if( paperbd != null ) setMotif( paperbd, scale );
		}
		
		//________________________________________________________________________
		//																  PRIVATES
		
		private function initMovie( baseMaterial:BitmapMaterial, quality : Number ) : void
        {
            wallLayer = new Bitmap( baseMaterial.bitmap );
            wallLayer.scaleX = wallLayer.scaleY = quality;
			paperLayer = new Sprite();
			wpmovie = new Sprite();
			
			paperLayer.blendMode = BlendMode.MULTIPLY;
			
			wpmovie.addChild( wallLayer );
			wpmovie.addChild( paperLayer );
        }
		
		private var wpmovie : 		Sprite;
		private var wallLayer : 	Bitmap;
		private var paperbd : 		BitmapData;
		private var _scale : 		Number = 1;
		private var quality : 		Number = 1;
		
	}
}